package com.lagou.edu.servlet;

import com.lagou.edu.factory.AnnotationBeanFactory;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.service.impl.TransferServiceImpl2;
import com.lagou.edu.service.impl.TransferServiceImpl3;
import com.lagou.edu.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 应癫
 */
@WebServlet(name="transferServlet",urlPatterns = "/transferServlet",loadOnStartup = 1)
public class TransferServlet extends HttpServlet {

    private TransferService transferService;
    private TransferServiceImpl2 transferService2;
    private TransferServiceImpl3 transferService3;

    @Override
    public void init() throws ServletException {
        System.out.println("init TransferServlet...");
        AnnotationBeanFactory beanFactory = (AnnotationBeanFactory) this.getServletContext().getAttribute("beanFactory");

        transferService = beanFactory.getBeanByType(TransferService.class);
        System.out.println("inject transferService, class=" + transferService.getClass());

        // 演示不实现接口走CGLIB代理情况
        transferService2 = beanFactory.getBeanByType(TransferServiceImpl2.class);
        System.out.println("inject transferService2, class=" + transferService2.getClass());

        // 演示自定义Bean ID的情况
        transferService3 = beanFactory.getBeanById("helloSpring");
        System.out.println("inject transferService3, class=" + transferService3.getClass());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();
        try {
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
